import React, { useState } from 'react'; // 添加useState
import { Form, Input, Select, Button, message, Card } from 'antd';
import { UserOutlined, LockOutlined, BookOutlined } from '@ant-design/icons';
import { register } from '../API/authAPI';

const { Option } = Select;

const RegisterPage = () => {
  const [form] = Form.useForm();
  // 添加用户类型状态管理
  const [userType, setUserType] = useState(null);

  const onFinish = async (values) => {
    try {
      // 移除confirmPassword字段，后端不需要
      const { confirmPassword, ...registerData } = values;
      
      // 构造教师信息对象
      let teacherInfo = null;
      if (registerData.userType === 'teacher') {
        teacherInfo = {
          subject: registerData.subject,
          // full_name字段将在后续表单完善中添加
        };
        // 从主数据中移除subject，它属于teacherInfo
        delete registerData.subject;
      }
      
      // 调用注册API - 修正参数传递方式
      await register(
        registerData.username,
        registerData.password,
        registerData.userType,
        teacherInfo
      );
      
      message.success('注册成功！请前往登录');
      form.resetFields();
    } catch (error) {
      message.error(`注册失败: ${error.message || '服务器错误'}`);
    }
  };

  // 处理用户类型变更
  const handleUserTypeChange = (value) => {
    setUserType(value);
  };

  return (
    <Card
      title="成绩分析系统 - 注册"
      bordered
      hoverable
      style={{ maxWidth: 300, margin: '100px auto', boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)' }}
    >
      <Form
        form={form}
        name="register_form"
        onFinish={onFinish}
        layout="vertical"
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[
            { required: true, message: '请输入用户名!' },
            { min: 2, max: 20, message: '用户名长度必须在2-20个字符之间!' },
            { pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/, message: '用户名只能包含字母、数字和中文!' }
          ]}
        >
          <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[
            { required: true, message: '请输入密码!' },
            { min: 8, message: '密码长度不能少于8个字符!' },
            { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).+$/, message: '密码必须包含大小写字母和数字!' }
          ]}
        >
          <Input prefix={<LockOutlined />} type="password" placeholder="请输入密码" />
        </Form.Item>

        <Form.Item
          name="confirmPassword"
          label="确认密码"
          dependencies={['password']}
          rules={[
            { required: true, message: '请确认密码!' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致!'));
              },
            }),
          ]}
        >
          <Input prefix={<LockOutlined />} type="password" placeholder="请确认密码" />
        </Form.Item>

        <Form.Item
          name="userType"
          label="用户类型"
          rules={[{ required: true, message: '请选择用户类型!' }]}
        >
          <Select 
            placeholder="请选择用户类型"
            onChange={handleUserTypeChange} // 添加变更监听
          >
            <Option value="teacher">教师</Option>
            <Option value="admin">管理员</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="subject"
          label="任教科目"
          dependencies={['userType']}
          shouldUpdate={(prevValues, currentValues) => prevValues.userType !== currentValues.userType}
          rules={[
            ({ getFieldValue }) => (
              getFieldValue('userType') === 'teacher'
                ? { required: true, message: '请选择任教科目!' }
                : []
            ),
          ]}
        >
          <Select 
            placeholder="请选择任教科目" 
            disabled={userType !== 'teacher'} // 使用状态变量判断
          >
            <Option value="math">数学</Option>
            <Option value="chinese">语文</Option>
            <Option value="english">英语</Option>
            <Option value="physics">物理</Option>
            <Option value="chemistry">化学</Option>
            <Option value="biology">生物</Option>
            <Option value="history">历史</Option>
            <Option value="geography">地理</Option>
            <Option value="politics">政治</Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
            注册
          </Button>
        </Form.Item>
      </Form>
    </Card>
  );
};

export default RegisterPage;
